<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/5
 * Time: 13:48
 */
namespace app\index\controller;

use think\Db;
use think\Request;

class Orders extends Common
{
	//判断是否登录
	public function _initialize()
	{
		parent::_initialize();
	}
	
	/**
	 * 结算首页
	 * @param string sid 店铺id
	*/
	public function index()
	{
		$sid = input('get.sid');
		return view('index',compact('sid'));
	}
	/**
	 * 商品结算
	 * @param string barcode 商品二维码
	 * @return json result 商品信息
	 * @return json error 商品不存在
	*/
	public function barcode()
	{
		if(Request()->isAjax()){
			$barcode = input('barcode');
			$result = Db::table('product')->where('barcode',$barcode)->where('status',7)->find();
			if(!$result){
				$error = ['error'=>'商品不存在'];
				return json($error);
			}
			return json($result);
		}
	}
	
	/**
	 * 结算
	 * @param string post.total 商品购买信息;
	 * @param string post.sid 线下店铺id
	 * @return json success 结算成功  error 结算失败错误信息
	*/
	public function settlement()
	{
		if(Request()->isAjax()){
			try{
				$total = json_decode(input('post.total'));
				$sid = input('post.sid');
				$payment = input('post.paymethod');
				//订单号
				$input['ordernumber'] = time();
				//下单时间
				$input['date'] = time();
				Db::startTrans();
				for($i=0;$i<count($total);$i++){
					//支付方式
					$input['payment'] = $payment;
					//商品id
					$input['pid'] = $total[$i][0];
					//线下店铺id
					$input['sid'] = $sid;
					//商品单价
					$input['retailprice'] = $total[$i][1];
					//购买数量
					$input['number'] = $total[$i][2];
					//条形码
					$input['barcode'] = $total[$i][3];
					//商品名称
					$input['pname'] = $total[$i][4];
					//商品图片
					$input['image'] = $total[$i][5];
					//合计
					$input['total'] = $total[$i][6];
					$info = Db::table('inventory')->where('sid',$sid)->where('pid',$input['pid'])->find();
					//增加卖出数
					$info['sellnumber'] = $info['sellnumber'] + $input['number'];
					$number = $info['number'] - $info['sellnumber'];
					if($number < 0){
						throw new \PDOException('库存存货不足');
					}
					//更新库存
					$res = Db::table('inventory')->where('sid',$sid)->where('pid',$input['pid'])->update(['sellnumber'=>$info['sellnumber']]);
					if(!$res){
						throw new \PDOException('库存修改失败');
					}
					$result[] = Db::table('order')->insertGetId($input);
					if(count($result) == 0){
						throw new \PDOException('订单添加失败');
					}
					
				}
				Db::commit();
//				$value = Db::table('address')->where('sid',$sid)->find();
//				$info = Db::table('order')->whereIn('id',$result)->select();
//				$orderInfo = $this->typesetting($info,14,7,3,$value['address']);
//				$resultMsg = json_decode(order_print($orderInfo,1,$value['printid']));
//				if($resultMsg -> ret != 0){
//					throw new \PDOException($resultMsg->msg);
//				}
				$success = ['success'=>'结算成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	/**
	 * 查看购买记录
	 * @param string get.sid 线下店铺id
	*/
	public function purchase()
	{
		$where = ['query'=>[]];
		$sid = input('get.sid');
		$db = Db::table('order')
			->join('shop','shop.id = order.sid','LEFT')
			->where('order.sid',$sid)
			->where('order.status',1)
			->group('order.ordernumber')
			->order('order.id desc');
		if(!empty(trim(input('get.title')))){
			$title = trim(input('get.title'));
			$db->where('ordernumber',"{$title}");
			$where['query']['title'] = $title;
		}
		if(!empty(input('get.start')) && !empty(input('get.end'))){
			$start = input('get.start');
			$end = input('get.end');
			$db->whereTime('date','between', ["{$start}", "{$end}"]);
			$where['query']['start'] = $start;
			$where['query']['end'] = $end;
			$count = Db::table('order')->whereTime('date','between', ["{$start}", "{$end}"])->where('sid',$sid)->where('status',1)->sum('total');
		}else{
			$date = date("Y-m-d",time());
			$data = explode('-',$date);
			$ret = getStartAndEndUnixTimestamp($data[0],$data[1],$data[2]);
			$db->whereTime('date','between', ["{$ret['start']}","{$ret['end']}"]);
			$where['query']['start'] = $ret['start'];
			$where['query']['end'] = $ret['end'];
			$count = Db::table('order')->whereTime('date','between',["{$ret['start']}","{$ret['end']}"])->where('sid',$sid)->where('status',1)->sum('total');
		
		}
		$where['query']['sid'] = $sid;
		$result = $db->paginate(8,false,$where);
		return view('purchase',compact('result','sid','date','count','title','start','end'));
		
	}
	
	/**
	 * 订单详情
	 * @param string get.ordernumber 订单号
	 * @param string get.sid 下线店id
	*/
	public function detail()
	{
		$sid = input('get.sid');
		$ordernumber = input('get.ordernumber');
		$result = Db::table('order')
			->field('product.purchaseprice,order.pname,order.retailprice,order.number,
					order.ordernumber,order.date,order.total,order.id,order.sid,order.pid')
			->join('product','product.id = order.pid','LEFT')
				->where('order.sid',$sid)
				->where('order.status',1)
				->where('order.ordernumber',$ordernumber)
				->paginate(8);
		return view('detail',compact('result'));
	}
	
	/**
	 * 删除订单
	 * @param string post.id  订单编号
	 * @return json success 删除成功 error  删除失败错误信息
	*/
	public function delete()
	{
		if(request()->isAjax()){
			try{
				$id = input('post.id');
				Db::startTrans();
				$result = Db::table('order')->where('id',$id)->update(['status'=>2]);
				if(!$result){
					throw new \PDOException('删除失败');
				}
				Db::commit();
				$success = ['success'=>'删除成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	
	
	
	/**
	 * 飞鹅云排版
	 * @param $arr 要排版的数据
	 * @param $A 名称14
	 * @param $B 单价7
	 * @param $C 数量3
	 */
	function typesetting($arr,$A,$B,$C,$address)
	{
		$nums = 0;
		$orderInfo = '<CB>新品有戏</CB><BR>';
		$orderInfo .= '名称           单价   数量<BR>';//名称14 单价7 数量3 金额6-->这里的字节数可按自己需求自由改写
		$orderInfo .= '--------------------------------<BR>';
		foreach ($arr as $k5 => $v5) {
			$name = $v5['pname'];
			$price = $v5['retailprice'];
			$num = $v5['number'];
			//$prices = $v5['classid'];
			$kw3 = '';
			$kw1 = '';
			$kw2 = '';
			$kw4 = '';
			$str = $name;
			$blankNum = $A;//名称控制为14个字节
			$lan = mb_strlen($str,'utf-8');
			$m = 0;
			$j=1;
			$blankNum++;
			$result = array();
			for ($i=0;$i<$lan;$i++){
				$new = mb_substr($str,$m,$j,'utf-8');
				$j++;
				if(mb_strwidth($new,'utf-8')<$blankNum) {
					if($m+$j>$lan) {
						$m = $m+$j;
						$tail = $new;
						$lenght = iconv("UTF-8", "GBK//IGNORE", $new);
						$k = $A - strlen($lenght);
						for($q=0;$q<$k;$q++){
							$kw3 .= ' ';
						}
						$tail .= $kw3;
						break;
					}else{
						$next_new = mb_substr($str,$m,$j,'utf-8');
						if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
						else{
							$m = $i+1;
							$result[] = $new.'<BR>';
							$j=1;
						}
					}
				}
			}
			$head = '';
			foreach ($result as $value) {
				$head .= $value;
			}
			if(strlen($price) < $B){
				$k1 = $B - strlen($price);
				for($q=0;$q<$k1;$q++){
					$kw1 .= ' ';
				}
				$price = $price.$kw1;
			}
			if(strlen($num) < $C){
				$k2 = $C - strlen($num);
				for($q=0;$q<$k2;$q++){
					$kw2 .= ' ';
				}
				$num = $num.$kw2;
			}
//			if(strlen($prices) < $D){
//				$k3 = $D - strlen($prices);
//				for($q=0;$q<$k3;$q++){
//					$kw4 .= ' ';
//				}
//				$prices = $prices.$kw4;
//			}
			$orderInfo .= $head.$tail.' '.$price.' '.$num.'<BR>';
			@$nums += $price * $num;
		}
		$time = date('Y-m-d H:i:s',time());
		$orderInfo .= '--------------------------------<BR>';
		$orderInfo .= '合计：'.$nums.'元<BR>';
		$orderInfo .= '卖出地址：'.$address.'<BR>';
		$orderInfo .= '购买时间：'.$time.'<BR>';
		$orderInfo .= '<QR>https://mp.weixin.qq.com/a/~TvISZDOmlZ9gC_3qVT7_fQ~~</QR>';
		return $orderInfo;
	}
    /**
	 * 添加订单备注
	 * @param string input('post.ordernumber') 订单号
	 * @param string input('post.remarks') 备注
    */
    public function remarks()
	{
		try{
			$ordernumber = input('post.ordernumber');
			$remarks = input('post.remarks');
			$result = Db::table('order')->where('ordernumber',$ordernumber)->update(['remarks'=>$remarks]);
			if(!$result){
				throw new \PDOException('添加失败');
			}
			$success = ['success'=>'添加成功'];
			return json($success);
		}catch (\PDOException $e){
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
}